/*
 * @Author: Leng
 * @Date: 2023-04-07 15:00:09
 * @Description: 请求拦截,响应拦截
 * @FilePath: \vue-leng\src\config\requestNew.js
 */

import axios from "axios"

const requestConfig = {
  // 导出配置
  apiConfig: null,

  // get请求
  get(instance, url, params, config) {
    return instance
      .get(url, params, config)
      .then((res) => {
        // return Promise.resolve((res && res.data) || {})
        return Promise.resolve((res) || {})
      })
      .catch((err) => {
        console.error(err)
        return Promise.resolve({
          code: "-404",
          msg: err.message || "网络异常",
        })
      })
  },

  // post请求
  post(instance, url, params, config = {}) {
    return instance
      .post(url, params, config)
      .then((res) => {
        // return Promise.resolve((res && res.data) || {})
        return Promise.resolve((res) || {})
      })
      .catch((err) => {
        console.error(err)
        return Promise.resolve({
          code: "-404",
          msg: err.message || "网络异常",
        })
      })
  },

  // 实例化
  createInstance() {
    const instance = axios.create({
      // H5前台
      // baseURL: window.$ZConfig.getServerUrl(),
      // admin后台
      baseURL: 'https://admin-uat.z-trip.cn',
      // withCredentials: true,
      // headers: {
      // 	'Access-Control-Allow-Credentials': "false",
      // 	'Access-Control-Allow-Origin': '*'
      // },
      timeout: 15 * 1000,
    })
    //请求拦截
    instance.interceptors.request.use(
      (config) => {
        // config.headers['ismock'] = false
        return config
      },
      (error) => {
        console.log(error)
        return Promise.reject(error)
      }
    )
    //响应拦截
    instance.interceptors.response.use(
      (response) => {
        const res = response.data
        if (res.code == "-99") {
          console.log(`未登录：${window.location.origin}/login`)
          return Promise.reject(new Error(res.message || "Error"))
        } else {
          return res
        }
      },
      (error) => {
        console.log("err" + error)
        return Promise.reject(error)
      }
    )
    // 导出配置
    this.apiConfig = {
      get: (...args) => {
        return this.get(instance, ...args)
      },
      post: (...args) => {
        return this.post(instance, ...args)
      },
      cancelToken: axios.CancelToken,
      instance,
    }
    return this.apiConfig
  }
}

// 创建实例
requestConfig.createInstance()
const requestApi = requestConfig.apiConfig

// 原有继承方式
class api {
  static get(url, params, config) {
    return requestApi.get(url, params, config)
  }

  static post(url, params, config) {
    return requestApi.post(url, params, config)
  }
}

export {
    api, 
    requestApi
}
